// A benchmark has a name (string) and a function that will be run to
// do the performance measurement. The optional setup and tearDown
// arguments are functions that will be invoked before and after
// running the benchmark, but the running time of these functions will
// not be accounted for in the benchmark score.

function Benchmark(name, run) {
  this.name = name;
  this.run = run;
  // this.Setup = setup ? setup : function() { };
  // this.TearDown = tearDown ? tearDown : function() { };
  this.Setup = function() { };
  this.TearDown = function() { };
}

// Benchmark results hold the benchmark and the measured time used to
// run the benchmark. The benchmark score is computed later once a
// full benchmark suite has run to completion.
function BenchmarkResult(benchmark, time) {
  this.benchmark = benchmark;
  this.time = time;
}

// Automatically convert results to numbers. Used by the geometric
// mean computation.

BenchmarkResult.prototype.valueOf = function() {
  return this.time;
};

// Suites of benchmarks consist of a name and the set of benchmarks in
// addition to the reference timing that the final score will be based
// on. This way, all scores are relative to a reference run and higher
// scores implies better performance.
function BenchmarkSuite(name, reference, benchmarks) {
  this.name = name;
  this.reference = reference;
  this.benchmarks = benchmarks;
  BenchmarkSuite.suites.push(this);
}


// Keep track of all declared benchmark suites.
BenchmarkSuite.suites = [];





// Scores are not comparable across versions. Bump the version if
// you're making changes that will affect that scores, e.g. if you add
// a new benchmark or change an existing one.
BenchmarkSuite.version = '7';

Math.random = function(){
  var seed = 49734321;
  seed = ((seed + 0x7ed55d16) + (seed << 12))  & 0xffffffff;
  seed = ((seed ^ 0xc761c23c) ^ (seed >> 19)) & 0xffffffff;
  seed = ((seed + 0x165667b1) + (seed << 5))   & 0xffffffff;
  seed = ((seed + 0xd3a2646c) ^ (seed << 9))   & 0xffffffff;
  seed = ((seed + 0xfd7046c5) + (seed << 3))   & 0xffffffff;
  seed = ((seed ^ 0xb55a4f09) ^ (seed >> 16)) & 0xffffffff;
  return (seed & 0xfffffff) / 0x10000000;
};

// Runs all registered benchmark suites and optionally yields between
// each individual benchmark to avoid running for too long in the
// context of browsers. Once done, the final score is reported to the
// runner.
BenchmarkSuite.RunSuites = function(runner) {
  
  var suites = BenchmarkSuite.suites;
  var length = suites.length;
  BenchmarkSuite.scores = [];
  var index = 0;
  function RunStep() {
    var continuation = null;
    while (continuation || index < length) {
      if (continuation) {
        
        continuation = continuation();
        
      } else {
        var suite = suites[index++];
        
        if (runner.NotifyStart) runner.NotifyStart(suite.name);
        continuation = suite.RunStep(runner);
      }
      // if (continuation && typeof window != 'undefined' && window.setTimeout) {
      //   window.setTimeout(RunStep, 25);
      //   return;
      // }
    }
    
    if (runner.NotifyScore) {
      // var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
      // var formatted = BenchmarkSuite.FormatScore(100 * score);
      var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
      runner.NotifyScore(100 * score);
    }
  }
  RunStep();
};

// Counts the total number of registered benchmarks. Useful for
// showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = function() {
  var result = 0;
  var suites = BenchmarkSuite.suites;
  for (var i = 0; i < suites.length; i++) {
    result += suites[i].benchmarks.length;
  }
  return result;
};


// Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = function(numbers) {
  var log = 0;
  for (var i = 0; i < numbers.length; i++) {
    print(typeof numbers[i])
    if( typeof numbers[i] == 'number' ){
      log += Math.log(numbers[i]);
      print("GeometricMean", numbers[i])
    }
    else{
      log += Math.log(numbers[i].time);
    }
  }
  return Math.pow(Math.E, log / numbers.length);
};


// Converts a score value to a string with at least three significant
// digits.
BenchmarkSuite.FormatScore = function(value) {
  if (value > 100) {
    return value.toFixed(0);
  } else {
    return value.toPrecision(3);
  }
};

// Notifies the runner that we're done running a single benchmark in
// the benchmark suite. This can be useful to report progress.
BenchmarkSuite.prototype.NotifyStep = function(result) {
  this.results.push(result);
  if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
};


// Notifies the runner that we're done with running a suite and that
// we have a result which can be reported to the user if needed.
BenchmarkSuite.prototype.NotifyResult = function() {
  var mean = BenchmarkSuite.GeometricMean(this.results);
  var score = this.reference / mean;
  BenchmarkSuite.scores.push(score);
  
  if (this.runner.NotifyResult) {
    // var formatted = BenchmarkSuite.FormatScore(100 * score);
    // this.runner.NotifyResult(this.name, formatted);
    this.runner.NotifyResult(this.name, 100 * score);
  }
};


// Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite.prototype.NotifyError = function(error) {
  if (this.runner.NotifyError) {
    this.runner.NotifyError(this.name, error);
  }
  if (this.runner.NotifyStep) {
    this.runner.NotifyStep(this.name);
  }
};


// Runs a single benchmark for at least a second and computes the
// average time it takes to run a single iteration.
BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  function Measure(data) {

    var elapsed = 0;
    var start = clock() * 1000;
    // var start = new Date();
    for (var n = 0; elapsed < 1000; n++) {
      benchmark.run();
      elapsed = clock() * 1000 - start;
      // elapsed = new Date() - start
    }
    
    if (data != null) {
      data.runs = data.runs + n;
      data.elapsed = data.elapsed + elapsed;
    }
  }

  if (data == null) {
    // Measure the benchmark once for warm up and throw the result
    // away. Return a fresh data object.
    Measure(null);
    return { runs: 0, elapsed: 0 };
  } else {
    
    Measure(data);
    // If we've run too few iterations, we continue for another second.
    if (data.runs < 32) return data;
    print(data.runs)
    var usec = (data.elapsed * 1000) / data.runs;
    this.NotifyStep(new BenchmarkResult(benchmark, usec));
    return null;
  }
};


// This function starts running a suite, but stops between each
// individual benchmark in the suite and returns a continuation
// function which can be invoked to run the next benchmark. Once the
// last benchmark has been executed, null is returned.
BenchmarkSuite.prototype.RunStep = function(runner) {
  this.results = [];
  this.runner = runner;
  var length = this.benchmarks.length;
  var index = 0;
  var suite = this;
  var data = null;
  // Run the setup, the actual benchmark, and the tear down in three
  // separate steps to allow the framework to yield between any of the
  // steps.
  function RunNextSetup() {
    if (index < length) {
      suite.benchmarks[index].Setup();
      return RunNextBenchmark;
    }
    suite.NotifyResult();
    return null;
  }

  function RunNextBenchmark() {
    data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
    // If data is null, we're done with this benchmark.
    if( data == null ) return RunNextTearDown;
    else return RunNextBenchmark();
    //return (data == null) ? RunNextTearDown : RunNextBenchmark();
  }

  function RunNextTearDown() {
    suite.benchmarks[index++].TearDown();
    return RunNextSetup;
  }

  // Start out running the setup.
  return RunNextSetup();
};

/**
 * The Richards benchmark simulates the task dispatcher of an
 * operating system.
 **/
function runRichards() {
  var scheduler = new Scheduler();
  scheduler.addIdleTask(ID_IDLE, 0, null, 1000);

  var queue = new Packet(null, ID_WORKER, KIND_WORK);
  queue = new Packet(queue,  ID_WORKER, KIND_WORK);

  scheduler.addWorkerTask(ID_WORKER, 1000, queue);

  queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE);
  queue = new Packet(queue,  ID_DEVICE_A, KIND_DEVICE);
  queue = new Packet(queue,  ID_DEVICE_A, KIND_DEVICE);
  scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue);


  queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE);
  queue = new Packet(queue,  ID_DEVICE_B, KIND_DEVICE);
  queue = new Packet(queue,  ID_DEVICE_B, KIND_DEVICE);
  scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue);

  scheduler.addDeviceTask(ID_DEVICE_A, 4000, null);

  scheduler.addDeviceTask(ID_DEVICE_B, 5000, null);

  scheduler.schedule();
  if (scheduler.queueCount != EXPECTED_QUEUE_COUNT ||
      scheduler.holdCount != EXPECTED_HOLD_COUNT) {
    print('Error during execution: queueCount = ', scheduler.queueCount, scheduler.holdCount);
    // var msg =
    //     "Error during execution: queueCount = " + scheduler.queueCount +
    //     ", holdCount = " + scheduler.holdCount + ".";
    // throw new Error(msg);
  }
}

var COUNT = 1000;

/**
 * These two constants specify how many times a packet is queued and
 * how many times a task is put on hold in a correct run of richards.
 * They don't have any meaning a such but are characteristic of a
 * correct run so if the actual queue or hold count is different from
 * the expected there must be a bug in the implementation.
 **/
var EXPECTED_QUEUE_COUNT = 2322;
var EXPECTED_HOLD_COUNT = 928;


/**
 * A scheduler can be used to schedule a set of tasks based on their relative
 * priorities.  Scheduling is done by maintaining a list of task control blocks
 * which holds tasks and the data queue they are processing.
 * @constructor
 */
function Scheduler() {
  var that = this;
  that.queueCount = 0;
  that.holdCount = 0;
  that.blocks = new Array(6);
  that.list = null;
  that.currentTcb = null;
  that.currentId = null;
}

var ID_IDLE       = 0;
var ID_WORKER     = 1;
var ID_HANDLER_A  = 2;
var ID_HANDLER_B  = 3;
var ID_DEVICE_A   = 4;
var ID_DEVICE_B   = 5;
var NUMBER_OF_IDS = 6;

var KIND_DEVICE   = 0;
var KIND_WORK     = 1;

/**
 * Add an idle task to this scheduler.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 * @param {int} count the number of times to schedule the task
 */
Scheduler.prototype.addIdleTask = function (id, priority, queue, count) {
  var that = this;
  that.addRunningTask(id, priority, queue, new IdleTask(that, 1, count));
};

/**
 * Add a work task to this scheduler.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 */
Scheduler.prototype.addWorkerTask = function (id, priority, queue) {
  var that = this;
  that.addTask(id, priority, queue, new WorkerTask(that, 2, 0));
};

/**
 * Add a handler task to this scheduler.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 */
Scheduler.prototype.addHandlerTask = function (id, priority, queue) {
  var that = this;
  that.addTask(id, priority, queue, new HandlerTask(that));
};

/**
 * Add a handler task to this scheduler.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 */
Scheduler.prototype.addDeviceTask = function (id, priority, queue) {
  var that = this;
  that.addTask(id, priority, queue, new DeviceTask(that));
};

/**
 * Add the specified task and mark it as running.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 * @param {Task} task the task to add
 */
Scheduler.prototype.addRunningTask = function (id, priority, queue, task) {
  var that = this;
  that.addTask(id, priority, queue, task);
  that.currentTcb.setRunning();
};

/**
 * Add the specified task to this scheduler.
 * @param {int} id the identity of the task
 * @param {int} priority the task's priority
 * @param {Packet} queue the queue of work to be processed by the task
 * @param {Task} task the task to add
 */
Scheduler.prototype.addTask = function (id, priority, queue, task) {
  var that = this;
  that.currentTcb = new TaskControlBlock(that.list, id, priority, queue, task);
  var currentTcb = that.currentTcb;
  that.list = currentTcb;
  that.blocks[id] = currentTcb;
};

/**
 * Execute the tasks managed by this scheduler.
 */
Scheduler.prototype.schedule = function () {
  var that = this;
  that.currentTcb = that.list;
  while (that.currentTcb != null) {
    var currentTcb = that.currentTcb;
    if (currentTcb.isHeldOrSuspended()) {
      that.currentTcb = currentTcb.link;
    } else {
      that.currentId = currentTcb.id;
      that.currentTcb = currentTcb.run();
    }
  }
};

/**
 * Release a task that is currently blocked and return the next block to run.
 * @param {int} id the id of the task to suspend
 */
Scheduler.prototype.release = function (id) {
  var that = this;
  var tcb = that.blocks[id];
  if (tcb == null) return tcb;
  tcb.markAsNotHeld();
  var currentTcb = that.currentTcb;
  if (tcb.priority > currentTcb.priority) {
    return tcb;
  } else {
    return currentTcb;
  }
};

/**
 * Block the currently executing task and return the next task control block
 * to run.  The blocked task will not be made runnable until it is explicitly
 * released, even if new work is added to it.
 */
Scheduler.prototype.holdCurrent = function () {
  var that = this;
  var currentTcb = that.currentTcb;
  that.holdCount++;
  currentTcb.markAsHeld();
  return currentTcb.link;
};

/**
 * Suspend the currently executing task and return the next task control block
 * to run.  If new work is added to the suspended task it will be made runnable.
 */
Scheduler.prototype.suspendCurrent = function () {
  var currentTcb = this.currentTcb;
  currentTcb.markAsSuspended();
  return currentTcb;
};

/**
 * Add the specified packet to the end of the worklist used by the task
 * associated with the packet and make the task runnable if it is currently
 * suspended.
 * @param {Packet} packet the packet to add
 */
Scheduler.prototype.queue = function (packet) {
  var that = this;
  var t = that.blocks[packet.id];
  if (t == null) return t;
  that.queueCount++;
  
  packet.link = null;
  packet.id = that.currentId;
  return t.checkPriorityAdd(that.currentTcb, packet);
};

/**
 * A task control block manages a task and the queue of work packages associated
 * with it.
 * @param {TaskControlBlock} link the preceding block in the linked block list
 * @param {int} id the id of this block
 * @param {int} priority the priority of this block
 * @param {Packet} queue the queue of packages to be processed by the task
 * @param {Task} task the task
 * @constructor
 */
function TaskControlBlock(link, id, priority, queue, task) {
  var that = this;
  that.link = link;
  that.id = id;
  that.priority = priority;
  that.queue = queue;
  that.task = task;
  if (queue == null) {
    that.state = 2;
  } else {
    that.state = 3;
  }
}

/**
 * The task is running and is currently scheduled.
 */
var STATE_RUNNING = 0;

/**
 * The task has packets left to process.
 */
var STATE_RUNNABLE = 1;

/**
 * The task is not currently running.  The task is not blocked as such and may
* be started by the scheduler.
 */
var STATE_SUSPENDED = 2;

/**
 * The task is blocked and cannot be run until it is explicitly released.
 */
var STATE_HELD = 4;

var STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE;
var STATE_NOT_HELD = ~STATE_HELD;

TaskControlBlock.prototype.setRunning = function () {
  this.state = 0;
};

TaskControlBlock.prototype.markAsNotHeld = function () {
  var that = this;
  that.state = that.state & -5;
};

TaskControlBlock.prototype.markAsHeld = function () {
  var that = this;
  that.state = that.state | 4;
};

TaskControlBlock.prototype.isHeldOrSuspended = function () {
  return (this.state & 4) != 0 || (this.state == 2);
};

TaskControlBlock.prototype.markAsSuspended = function () {
  var that = this;
  that.state = that.state | 2;
};

TaskControlBlock.prototype.markAsRunnable = function () {
  var that = this;
  that.state = that.state | 1;
};

/**
 * Runs this task, if it is ready to be run, and returns the next task to run.
 */
TaskControlBlock.prototype.run = function () {
  var that = this;
  var packet;
  if (that.state == 3) {
    packet = that.queue;
    that.queue = packet.link;
    if (that.queue == null) {
      that.state = 0;
    } else {
      that.state = 1;
    }
  } else {
    packet = null;
  }
  return that.task.run(packet);
};

/**
 * Adds a packet to the worklist of this block's task, marks this as runnable if
 * necessary, and returns the next runnable object to run (the one
 * with the highest priority).
 */
TaskControlBlock.prototype.checkPriorityAdd = function (task, packet) {
  var that = this;
  if (that.queue == null) {
    that.queue = packet;
    that.markAsRunnable();
    if (that.priority > task.priority) return that;
  } else {
    that.queue = packet.addTo(that.queue);
  }
  return task;
};

TaskControlBlock.prototype.toString = function () {
  return "tcb { " + this.task + "@" + this.state + " }";
};

/**
 * An idle task doesn't do any work itself but cycles control between the two
 * device tasks.
 * @param {Scheduler} scheduler the scheduler that manages this task
 * @param {int} v1 a seed value that controls how the device tasks are scheduled
 * @param {int} count the number of times this task should be scheduled
 * @constructor
 */
function IdleTask(scheduler, v1, count) {
  var that = this;
  that.scheduler = scheduler;
  that.v1 = v1;
  that.count = count;
}

IdleTask.prototype.run = function (packet) {
  var that = this;
  that.count--;
  if (that.count == 0) return that.scheduler.holdCurrent();
  var that_v1 = that.v1;
  if ((that_v1 & 1) == 0) {
    that.v1 = that_v1 >> 1;
    return that.scheduler.release(4);
  } else {
    that.v1 = (that_v1 >> 1) ^ 0xD008;
    return that.scheduler.release(5);
  }
};

IdleTask.prototype.toString = function () {
  return "IdleTask";
};

/**
 * A task that suspends itself after each time it has been run to simulate
 * waiting for data from an external device.
 * @param {Scheduler} scheduler the scheduler that manages this task
 * @constructor
 */
function DeviceTask(scheduler) {
  var that = this;
  that.scheduler = scheduler;
  that.v1 = null;
}

DeviceTask.prototype.run = function (packet) {
  var that = this;
  var that_v1 = that.v1
  if (packet == null) {
    if (that_v1 == null) return that.scheduler.suspendCurrent();
    var v = that_v1;
    that.v1 = null;
    return that.scheduler.queue(v);
  } else {
    that.v1 = packet;
    return that.scheduler.holdCurrent();
  }
};

DeviceTask.prototype.toString = function () {
  return "DeviceTask";
};

/**
 * A task that manipulates work packets.
 * @param {Scheduler} scheduler the scheduler that manages this task
 * @param {int} v1 a seed used to specify how work packets are manipulated
 * @param {int} v2 another seed used to specify how work packets are manipulated
 * @constructor
 */
function WorkerTask(scheduler, v1, v2) {
  var that = this;
  that.scheduler = scheduler;
  that.v1 = v1;
  that.v2 = v2;
}

WorkerTask.prototype.run = function (packet) {
  var that = this;
  if (packet == null) {
    return that.scheduler.suspendCurrent();
  } else {
    if (that.v1 == 2) {
      that.v1 = 3;
    } else {
      that.v1 = 2;
    }
    packet.id = that.v1;
    packet.a1 = 0;
    for (var i = 0; i < 4; i++) {
      that.v2++;
      if (that.v2 > 26) that.v2 = 1;
      packet.a2[i] = that.v2;
    }
    return that.scheduler.queue(packet);
  }
};

WorkerTask.prototype.toString = function () {
  return "WorkerTask";
};

/**
 * A task that manipulates work packets and then suspends itself.
 * @param {Scheduler} scheduler the scheduler that manages this task
 * @constructor
 */
function HandlerTask(scheduler) {
  var that = this;
  that.scheduler = scheduler;
  that.v1 = null;
  that.v2 = null;
}

HandlerTask.prototype.run = function (packet) {
  var that = this;
  if (packet != null) {
    if (packet.kind == 1) {
      that.v1 = packet.addTo(that.v1);
    } else {
      that.v2 = packet.addTo(that.v2);
    }
  }

  if (that.v1 != null) {
    var that_v1 = that.v1;
    var count = that_v1.a1;
    var v;
    if (count < 4) {
      if (that.v2 != null) {
        v = that.v2;
        that.v2 = that.v2.link;
        v.a1 = that_v1.a2[count];
        that_v1.a1 = count + 1;
        return that.scheduler.queue(v);
      }
    } else {
      v = that_v1;
      that.v1 = that_v1.link;
      return that.scheduler.queue(v);
    }
  }
  return that.scheduler.suspendCurrent();
};

HandlerTask.prototype.toString = function () {
  return "HandlerTask";
};

/* --- *
 * P a c k e t
 * --- */

var DATA_SIZE = 4;

/**
 * A simple package of data that is manipulated by the tasks.  The exact layout
 * of the payload data carried by a packet is not importaint, and neither is the
 * nature of the work performed on packets by the tasks.
 *
 * Besides carrying data, packets form linked lists and are hence used both as
 * data and worklists.
 * @param {Packet} link the tail of the linked list of packets
 * @param {int} id an ID for this packet
 * @param {int} kind the type of this packet
 * @constructor
 */
function Packet(link, id, kind) {
  var that = this;
  that.link = link;
  that.id = id;
  that.kind = kind;
  that.a1 = 0;
  that.a2 = new Array(4);
}

/**
 * Add this packet to the end of a worklist, and return the worklist.
 * @param {Packet} queue the worklist to add this packet to
 */
Packet.prototype.addTo = function (queue) {
  var that = this;
  that.link = null;
  
  if (queue == null) return that;
  var peek, next = queue;
  while ((peek = next.link) != null)
    next = peek;
  next.link = that;
  return queue;
};

Packet.prototype.toString = function () {
  return "Packet";
};

var Richards = new BenchmarkSuite('Richards', 35302, [
  new Benchmark("Richards", runRichards)
]);

var harnessErrorCount = 0;

function ShowProgress(name) {
  print('PROGRESS', name);
}

function AddError(name, error) {
  print('ERROR', name, error);
  print(error.stack);
  harnessErrorCount++;
}

function AddResult(name, result) {
  print('RESULT', name, result);
}

function AddScore(score) {
  print('SCORE', score);
}


function Run() {
  BenchmarkSuite.RunSuites({ NotifyStep: ShowProgress,
                             NotifyError: AddError,
                             NotifyResult: AddResult,
                             NotifyScore: AddScore });
}

Run();
